import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import utils.DBUtils;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;

@WebServlet("/message/add2")
public class AddMessageServletV2 extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int result = -1;
        // 1.得到前端参数并效验
        String from = req.getParameter("from");
        String to = req.getParameter("to");
        String msg = req.getParameter("msg");
        if (StringUtils.hasLength(from) && StringUtils.hasLength(to)
                && StringUtils.hasLength(msg)) {
            // 2.将表白对象加入到集合
            // 2.1 得到 Connection
            Connection connection = DBUtils.getConnection();
            // 2.2 拼接 sql，创建执行器
            String sql = "insert into messages(`from`,`to`,`message`) values(?,?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, from);
            statement.setString(2, to);
            statement.setString(3, msg);
            // 2.3 执行执行器，并返回结果
            result = statement.executeUpdate();
            // 2.4 关闭资源
            DBUtils.close(null, statement, connection);
        }
        resp.setContentType("text/html; charset=utf-8");
        resp.getWriter().println(result);
    }
}